<template>
  <div class="customer-searchpick-container">
    <top-tip :tipcontent="tipcontent" />
    <div style="padding: 50px; text-align: center">
      <el-form :inline="true" :model="queryForm" @submit.prevent>
        <el-form-item label="检索客户">
          <el-input
            v-model.trim="queryForm.searchKey"
            clearable
            placeholder="请输入客户名称"
            :prefix-icon="Search"
            style="width: 500px"
            @input="replaceHandle"
            @keyup.enter="queryData"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="big"
            :icon="Search"
            type="primary"
            @click="queryData"
          >
            查询
          </el-button>
          <el-button
            v-if="
              (queryForm.searchKey !== '' && doSearch && total === 0) ||
              allname === 0
            "
            :icon="Plus"
            type="danger"
            @click="CustomerHandle"
          >
            添加一个新客户
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- border
      lazy
      :tree-props="{ children: 'BusinessOrders', hasChildren: 'hasChildren' }" -->
    <div
      v-for="(item, index) in list"
      :key="index"
      v-loading="listLoading"
      style="
        width: 100%;
        margin-bottom: 10px;
        padding: 10px;
        border: 1px solid #e0e0e0;
        cursor: pointer;
      "
    >
      <div
        style="padding: 0px 0px 30px 0px; display: flex; align-items: center"
      >
        <!-- id -->
        <div style="width: 100px; font-size: 15px; width: 30px">
          {{ item.CustomerID }}
        </div>
        <!-- 名字 -->
        <div
          style="
            margin-left: 20px;
            width: 200px;
            font-size: 15px;
            color: #ff6600;
          "
          @click="showBusiness(index)"
        >
          {{ item.CustomerAllName }}
        </div>
        <!-- 打标 -->
        <div style="margin-left: 20px; width: 200px; font-size: 15px">
          <el-tag v-for="(itm, idx) in item.CustomerMarks" :key="idx">
            {{ itm }}
          </el-tag>
        </div>
        <!-- 城市 -->
        <div
          style="
            margin-left: 20px;
            font-size: 15px;
            width: 200px;
            flex-wrap: wrap;
          "
        >
          {{ item.Address }}
        </div>
        <!-- 区域 -->
        <div
          style="
            margin-left: 20px;
            width: 200px;
            font-size: 15px;
            flex-wrap: wrap;
          "
        >
          {{ item.City }}
        </div>
        <!--行业 -->
        <div
          style="
            margin-left: 20px;
            font-size: 15px;
            flex-wrap: wrap;
            width: 300px;
          "
        >
          {{ item.Industry }}
        </div>
        <!-- 按钮 -->
        <div style="flex: 1; text-align: right">
          <el-button type="danger" @click="showBusiness(index)">
            挑入推荐商机
          </el-button>
          <el-button
            v-if="item.PickStaffID === 0"
            type="primary"
            @click="applyPick(item, 0)"
          >
            自建商机挑入
          </el-button>
          <el-button v-else type="primary" @click="applyPick(item, 1)">
            自建商机挑入
          </el-button>
        </div>
      </div>
      <el-table v-if="item.show" :data="item.BusinessOrders">
        <el-table-column
          align="center"
          label="商机ID"
          prop="OrderID"
          width="100"
        />
        <el-table-column
          align="center"
          label="推荐商机"
          prop="BusinessOrderName"
        />
        <el-table-column align="center" label="商机类型">
          <template #default="{ row }">
            <div v-if="row.BusinessOrderType == 0" style="color: dodgerblue">
              新签商机
            </div>
            <div v-if="row.BusinessOrderType == 2" style="color: #ff6600">
              回签商机
            </div>
            <div v-if="row.BusinessOrderType == 2" style="color: #999">
              <br />
              {{ row.OrderProductName }}
              <br />
              上次到期时间：{{ row.upOrderEndDate }}
            </div>
            <div v-if="row.BusinessOrderType == 9" style="color: #ff6600">
              老系统合同
            </div>
            <div v-if="row.BusinessOrderType == 9" style="color: #000">
              <div v-for="(itm, idx) in row.OrderList" :key="idx">
                {{ itm.ProductName }}
                <br />
                {{ itm.ServiceStartDate }}至{{ itm.ServiceEndDate }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商机状态">
          <template #default="{ row }">
            <span v-if="row.OrderState == 0 && row.SaleStaffID == 0"></span>
            <span v-if="row.OrderState == 0 && row.SaleStaffID !== 0">
              跟进中
            </span>
            <span v-if="row.OrderState > 0">已签约</span>
            <span v-if="row.OrderState == -98">已被调配</span>
            <span v-if="row.OrderState == -99">已被撞走</span>
            <span v-if="row.OrderState == -100">已主动放弃</span>
            <span v-if="row.OrderState < -100">流出商机</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="挑入跟进人">
          <template #default="{ row }">
            <span v-if="row.SaleStaffID == 0"></span>
            <span v-else>***</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="申请挑入">
          <template #default="{ row }">
            <el-button
              v-if="
                row.isMainPick == 0 ||
                (row.isMainPick == 2 && row.OrderState == -100)
              "
              size="small"
              type="primary"
              @click="toBusiness(row)"
            >
              挑入商机
            </el-button>
            <el-button
              v-if="row.isMainPick == 1"
              size="small"
              type="success"
              @click="toBusiness(row)"
            >
              已挑入,去跟进
            </el-button>
            <el-button
              v-if="row.isMainPick == 2 && row.OrderState == 0"
              size="small"
              type="warning"
              @click="toBusiness(row)"
            >
              申请挑入
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="editRef" @fetch-data="fetchData" />
    <ApplySelection ref="ApplySelectionRef" />
    <!-- <customer ref="customerRef" @fetch-data="fetchData" /> -->
  </div>
</template>

<script>
  import ApplySelection from '@/views/customer/tracking/business/components/ApplySelection'
  import {
    getList,
    doDelete,
    ApplyCustomerPick,
    ApplyBusinessOrder,
  } from '@/api/customerSearchpick'
  import Edit from './components/CustomerSearchpickEdit'
  import TopTip from '@/components/TopTip'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'CustomerSearchpick',
    components: { Edit, TopTip, ApplySelection },
    setup() {
      const router = useRouter()
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        tipcontent: {
          title: '客户检索/申请挑入',
          memo:
            '销售人员如需开发客户，可在此进行客户检索，检索客户来源于公海；' +
            '检索到客户后，可进行申请挑入；如未检索到客户，可添加一个新的客户资源，添加后自动挑入到其名下！',
        },
        customerRef: null,
        editRef: null,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        doSearch: false,
        selectRows: '',
        ApplySelectionRef: null,
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          searchKey: '',
        },
        allname: 1,
      })

      watch(
        () => state.queryForm.searchKey,
        (newValue, oldValue) => {
          console.log(`State changed from ${oldValue} to ${newValue}`)
          // 这里可以添加你想要执行的代码
          if (newValue === '') {
            state.doSearch = false
          }
        }
      )
      const showBusiness = (index) => {
        state.list[index].show = !state.list[index].show
      }

      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const applyPick = async (row, num) => {
        // 没有挑入过
        if (num == 0) {
          const data = {
            CustomerID: row.CustomerID,
          }
          const {
            data: { CustomerPickID },
          } = await ApplyCustomerPick(data)
          router.push({
            path: '/customer/track/trackingBusiness',
            query: { CustomerPickID: CustomerPickID },
          })
        }
        // 挑入过 （直接跳转）
        if (num == 1) {
          console.log(row, 'rowrowrowrow')
          router.push({
            path: '/customer/track/trackingBusiness',
            query: { CustomerPickID: row.CustomerPickID },
          })
        }
        // if (row.PickStaffID === 0) {
        //   $baseConfirm('你确定要挑入吗', null, async () => {
        //     $baseConfirm(
        //       '挑入成功！\n请到我的跟进中客户里查看并跟进客户',
        //       null,
        //       async () => {
        //         router.push({
        //           path: '/customer/track/trackingBusiness',
        //           query: { CustomerPickID: row.CustomerPickID },
        //         })
        //       }
        //     )
        //   })
        // } else {
        //   $baseConfirm('此客户已被你挑入，你可以直接去跟进', null, async () => {
        //     router.push({
        //       path: '/customer/track/trackingBusiness',
        //       query: { CustomerPickID: row.CustomerPickID },
        //     })
        //   })
        // }
      }
      const handleDelete = (row) => {
        if (row.id) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            // const { msg } = await doDelete({ ids: row.id })
            $baseMessage('挑入成功！', 'success', 'vab-hey-message-success')
            await fetchData(state.queryForm.searchKey)
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.id).join()
            $baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData(state.queryForm.searchKey)
            })
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData(state.queryForm.searchKey)
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData(state.queryForm.searchKey)
      }
      const queryData = async () => {
        state.queryForm.pageNo = 1
        await fetchData(state.queryForm.searchKey)
        state.doSearch = true
      }
      const CustomerHandle = () => {
        state.queryForm.searchKey = state.queryForm.searchKey.replace(
          /[^\u4e00-\u9fa5a-zA-Z0-9]/g,
          ''
        )
        const row = {
          CustomerAllName: state.queryForm.searchKey,
        }
        state.editRef.showEdit(row)
      }
      const replaceHandle = (event) => {
        state.queryForm.searchKey = event.replace(
          /[^\u4e00-\u9fa5a-zA-Z0-9]/g,
          ''
        )
      }

      const fetchData = async (value) => {
        state.queryForm.searchKey = value
        console.log(state.queryForm)
        state.listLoading = true
        const {
          data: { allname, list, total },
        } = await getList(state.queryForm)
        state.list = list
        console.log(state.list, '    state.list    state.list')
        state.total = total
        state.allname = allname
        state.listLoading = false
      }
      const toBusiness = async (item) => {
        //没人挑入
        if (item.isMainPick == 0) {
          const dataMsg = {
            OrderID: item.OrderID,
          }
          const { data } = await ApplyBusinessOrder(dataMsg)

          router.push({
            path: '/customer/track/trackingBusiness',
            query: { CustomerPickID: data.CustomerPickID },
          })
        }
        // 自己挑入过的
        if (item.isMainPick == 1) {
          router.push({
            path: '/customer/track/trackingBusiness',
            query: { CustomerPickID: item.CustomerPickID },
          })
        }

        if (item.isMainPick == 2) {
          open(item.OrderID)
          console.log('有人挑入了 申请挑入')
        }
      }
      onMounted(() => {
        fetchData(state.queryForm.searchKey)
      })
      const open = (OrderID) => {
        ElMessageBox.confirm(
          '本商机已被他人正在跟进占用，你要申请此商机？',
          '提示',
          {
            confirmButtonText: '申请',
            cancelButtonText: '放弃',
            type: 'warning',
          }
        )
          .then(() => {
            console.log(state.form, 'state.form11')
            const dataMsg = {
              OrderID: OrderID,
            }
            state.ApplySelectionRef.showEdit(dataMsg)
          })
          .catch(() => {
            // ElMessage({
            //   type: 'info',
            //   message: 'Delete canceled',
            // })
          })
      }

      return {
        ...toRefs(state),
        showBusiness,
        open,
        setSelectRows,
        applyPick,
        CustomerHandle,
        handleDelete,
        toBusiness,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        Delete,
        Plus,
        Search,
        replaceHandle,
      }
    },
  })
</script>
